#!/usr/bin/env python

import wx

class Image(wx.Window):
    '''Image class
    
    @author Julot <andy.julot@gmail.com>
    @since Friday, April 13, 2012. 11:04 PM'''
    
    def __init__(self, parent):
        super(Image, self).__init__(parent, style=wx.BORDER_THEME)
        
        self.SetBackgroundColour('WHITE')
        
        self.pdc = wx.PseudoDC()
        
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.onSize)
    
    def OnPaint(self, event):
        # Create a buffered paint DC.  It will create the real
        # wx.PaintDC and then blit the bitmap to it when dc is
        # deleted.  
        dc = wx.BufferedPaintDC(self)
        # use PrepateDC to set position correctly
        # we need to clear the dc BEFORE calling PrepareDC
        bg = wx.Brush(self.GetBackgroundColour())
        dc.SetBackground(bg)
        dc.Clear()
        self.pdc.DrawToDC(dc)
        event.Skip()
    
    def onSize(self, event):
        self.draw(self._value)
        event.Skip()
        
    def clear(self):
        self.maxWidth = 1
        self.maxHeight = 1
        self.SetVirtualSize((self.maxWidth, self.maxHeight))
        
        self.pdc.BeginDrawing()
        self.pdc.Clear()
        self.pdc.EndDrawing()
        self.Refresh()
        self.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
    
    _value = None
    
    @property
    def value(self):
        return self._value
    
    @value.setter
    def value(self, value):
        self._value = value
        self.draw(value)
    
    def draw(self, image):
        self.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
        if not image: return
        
        self.Freeze()
        width, height = image.GetSize()
        if height > self.Size.height or width > self.Size.width:
            # Image needs resizing to fit the parent.
            # Use height as anchor.
            width, height = self.Size
            width = (height * image.Width) / image.Height
            if width > self.Size.width:
                width, height = self.Size
                # Width is still wider than the container, switch to width
                # as anchor.
                height = (width * image.Height) / image.Width
        x = (self.Size.width - width) / 2
        y = (self.Size.height - height) / 2
        image = image.ResampleBicubic(width, height)
        
        self.pdc.BeginDrawing()
        self.pdc.Clear()
        self.pdc.DrawBitmap(image.ConvertToBitmap(), x, y, False)
        self.pdc.EndDrawing()
        self.Refresh()
        self.Thaw()
        self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        